package co.edu.eam.iso.xml;

import java.math.BigDecimal;
import java.util.Map;
import java.util.Map.Entry;

import org.jdom.Attribute;
import org.jdom.Document;
import org.jdom.Element;

import co.edu.eam.iso.enums.CharacteristicEnum;
import co.edu.eam.iso.enums.ScaleEnum;
import co.edu.eam.iso.enums.SubCharacteristicEnum;
import co.edu.eam.iso.model.Characteristic;
import co.edu.eam.iso.model.Metric;
import co.edu.eam.iso.model.SubCharacteristic;

public class XMLGenerator {

	private static XMLGenerator instance = null;

	public Document generateXML(
			Map<CharacteristicEnum, Characteristic> characteristics,
			boolean includeValues) throws Exception {
		Element evaluation = new Element("evaluacion");
		
		Document document = new Document(evaluation);
		document.setRootElement(evaluation);

		for (Entry<CharacteristicEnum, Characteristic> characteristic : characteristics.entrySet()) {
			Element characteristicElement = new Element("caracteristica");
			characteristicElement.setAttribute(new Attribute("nombre", characteristic.getKey().toString()));
			
			BigDecimal characteristicValue = includeValues ? characteristic.getValue().getWeight() : BigDecimal.ZERO;
			characteristicElement.setAttribute(new Attribute("valor", characteristicValue.toString()));
			evaluation.addContent(characteristicElement);
			
			for (Entry<SubCharacteristicEnum, SubCharacteristic> subcharacteristicMap : characteristic
					.getValue().getSubcharacteristics().entrySet()) {
				Element subcharacteristicElement = new Element("subcaracteristica");
				subcharacteristicElement.setAttribute(new Attribute("nombre", subcharacteristicMap.getKey().toString()));
				
				BigDecimal subcharacteristicValue = includeValues ? subcharacteristicMap.getValue().getWeight() : BigDecimal.ZERO;
				subcharacteristicElement.setAttribute(new Attribute("valor", subcharacteristicValue.toString()));
				characteristicElement.addContent(subcharacteristicElement);
				
				for (Metric metric : subcharacteristicMap.getValue().getMetrics()) {
					Element metricElement = new Element("metrica");
					metricElement.setAttribute(new Attribute("descripcion", metric.getDescription()));
					
					ScaleEnum metricEvaluation = includeValues ? metric.getScale() : ScaleEnum.NOT_SELECTED;
					metricElement.setAttribute(new Attribute("evaluacion", metricEvaluation.toString()));
					subcharacteristicElement.addContent(metricElement);
				}
			}
		}
		
		return document;
	}

	public static XMLGenerator getInstance() {
		if (instance == null) {
			instance = new XMLGenerator();
		}
		return instance;
	}

}
